package com.link.gateway.core.utils;


import com.link.gateway.core.cllog.LCLogger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 * AES对称加密和解密
 * @author zhenghongda
 */
public class AesUtil {
    private AesUtil() {
    }

    private static final String AES_METHOD = "AES/GCM/NoPadding";

    private static final String AES_ECB_METHOD = "AES/ECB/PKCS5Padding";

    private static final String ENCODING = "utf-8";

    /**
     * AES加密，加密密码为默认密码
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc) throws Exception {

        return encrypt(sSrc, YmlConstants.getAesSecretkey());
    }

    /**
     * AES加密
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (StringUtils.isBlank(sKey)) {
            LCLogger.withException("加密密码为空！");
            return sSrc;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            LCLogger.withException("加密密码长度必须为16位！");
            return sSrc;
        }
        byte[] raw = sKey.getBytes(ENCODING);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance(AES_METHOD);//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] iv = cipher.getIV();
        assert iv.length == 12;
        byte[]  encryptData = cipher.doFinal(sSrc.getBytes());

        if (encryptData.length != sSrc.getBytes().length + 16) {
            throw  new IllegalArgumentException("sSrc 不可用");
        }
        byte[] message = new byte[12 + sSrc.getBytes().length + 16];
        System.arraycopy(iv, 0, message, 0, 12);
        System.arraycopy(encryptData, 0, message, 12, encryptData.length);

        return Base64.encodeBase64String(message);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    /**
     * AES解密，解密密码为默认密码
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc) {
        return decrypt(sSrc, YmlConstants.getAesSecretkey());
    }

    /**
     * AES解密
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey) {
        try {
            // 判断Key是否正确
            if (StringUtils.isBlank(sKey)) {
                LCLogger.withException("加密密码为空！");
                return sSrc;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                LCLogger.withException("加密密码长度必须是16位！");
                return sSrc;
            }
            byte[] raw = sKey.getBytes(ENCODING);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(AES_METHOD);
            byte[] message = Base64.decodeBase64(sSrc);
            if (message.length < 12 + 16) {
                throw new IllegalArgumentException();
            }
            GCMParameterSpec params = new GCMParameterSpec(128, message, 0, 12);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, params);
            byte[]  decryptData = cipher.doFinal(message, 12, message.length - 12);
            return new String(decryptData);
        } catch (Exception ex) {
            LCLogger.withException(ex.toString());
            return sSrc;
        }
    }


    /**
     * AES解密
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decryptToBase64(String sSrc, String sKey) {
        try {
            // 判断Key是否正确
            if (StringUtils.isBlank(sKey)) {
                LCLogger.withException("加密密码为空！");
                return sSrc;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                LCLogger.withException("加密密码长度必须是16位！");
                return sSrc;
            }
            byte[] raw = sKey.getBytes(ENCODING);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(AES_ECB_METHOD);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            //先用base64解密
            byte[] encrypted1 = Base64Utils.decode(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, ENCODING);
        } catch (Exception ex) {
            LCLogger.withException(ex.toString());
            return sSrc;
        }
    }

}
